//
//  QZRequest.m
//  shenBian
//
//  Created by 上官惠阳 on 15/8/18.
//  Copyright (c) 2015年 上官惠阳. All rights reserved.
//

#import "QZRequest.h"
#import "HTFHudHelper.h"
#import "QZCheckNetwork.h"

@implementation QZRequest


-(instancetype)init{
    
    self = [super init];
    if (self){
        self.isShowHUD = YES;
    }
    return self;
}

-(instancetype)init_QZrequestWithMethod:(id<QZRequestProtocol>)delegate
{
    self = [super init];
    if (self){
        self.isShowHUD = YES;
        //        self.delegate = delegate;
    }
    return self;
}
-(void )QZRequest_GET :(NSString *)urlString parameters:(id)parameters tagNSString:(NSString *)tag  stopRequest:(BOOL)stop isSerializer:(BOOL)ser isCache:(BOOL)isCache
{
        NSMutableString *caseKey = [NSMutableString stringWithString:urlString];
        NSArray *keys = [parameters allKeys];
        NSArray *values = [parameters allValues];
        for (int i = 0; i < keys.count; i ++) {
            [caseKey appendString:[NSString stringWithFormat:@"/%@=%@",keys[i],values[i]]];
        }
    
        if (![QZCheckNetwork isNetworkConnected]) {
            [[iToast makeText:@"请检查您的网络"]show];
            //没有连接网络就提取缓存里面数据
            if(isCache){
                if ([self.delegate respondsToSelector:@selector(request_GET_FinishValue:tagNSString:)]) {
                    id responseObject = [[TMCache sharedCache] objectForKey:caseKey];
                    if (responseObject) {//并且有缓存的情况下
                        [self.delegate request_GET_FinishValue:responseObject tagNSString:tag];
                    }
                }
            }
            return;
        }
    
    if (stop ==YES) {
        [_manager.operationQueue cancelAllOperations];
    }
    
    self.manager = [AFHTTPRequestOperationManager manager];
    
    //取消自动解析
    if (ser == YES) {
        self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    }else{
        self.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json",@"text/html", @"text/javascript", nil];
    }
    
    if(_isShowHUD){
        //菊花
        [[HTFHudHelper sharedInstance]showHudAcitivityOnWindow];
    }
    
    [_manager GET:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //隐藏菊花
        [[HTFHudHelper sharedInstance]hideHud];
        
        if(self.delegate && [self.delegate respondsToSelector:@selector(request_GET_FinishValue: tagNSString:)]){
            [self.delegate request_GET_FinishValue:responseObject tagNSString:tag];
            //数据请求成功就缓存起来吧
            if (isCache) {
                [[TMCache sharedCache] setObject:responseObject forKey:caseKey];
            }
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //隐藏菊花
        [[HTFHudHelper sharedInstance]hideHud];
        NSLog(@"Error: %@", error);
        NSLog(@"问题失败%@",operation);
        if (self.delegate && [self.delegate respondsToSelector:@selector(requestFailed:tagNSString:)]) {
            [self.delegate requestFailed:error tagNSString:tag];
        }
        
    }];
}
/**
 POST请求 参数ser 是否自解析 isCache是否加缓存
 */
-(void )QZRequest_POST :(NSString *)urlString parameters:(id)parameters tagNSString:(NSString *)tag  stopRequest:(BOOL)stop isSerializer:(BOOL)ser  isCache:(BOOL)isCache
{
    NSMutableString *caseKey = [NSMutableString stringWithString:urlString];
    NSArray *keys = [parameters allKeys];
    NSArray *values = [parameters allValues];
    for (int i = 0; i < keys.count; i ++) {
        [caseKey appendString:[NSString stringWithFormat:@"/%@=%@",keys[i],values[i]]];
    }
    
    if (![QZCheckNetwork isNetworkConnected]) {
        [[iToast makeText:@"请检查您的网络"]show];
        //没有连接网络就提取缓存里面数据
        if(isCache){
            if ([self.delegate respondsToSelector:@selector(request_POST_FinishValue: tagNSString:)]) {
                id responseObject = [[TMCache sharedCache] objectForKey:caseKey];
                if (responseObject) {//并且有缓存的情况下
                    [self.delegate request_POST_FinishValue:responseObject tagNSString:tag];
                }
                
            }
        }
        return;
    }
    
    if (stop ==YES) {
        [_manager.operationQueue cancelAllOperations];
    }
    
    self.manager = [AFHTTPRequestOperationManager manager];
    //取消自动解析
    if (ser == YES) {
        self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    }else{
        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json",@"text/html", @"text/javascript", nil];
    }
    if(_isShowHUD){
        //菊花
        [[HTFHudHelper sharedInstance]showHudAcitivityOnWindow];
    }
    [_manager POST:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //隐藏菊花
        [[HTFHudHelper sharedInstance]hideHud];
        
        if(self.delegate && [self.delegate respondsToSelector:@selector(request_POST_FinishValue: tagNSString:)]){
            [self.delegate request_POST_FinishValue:responseObject tagNSString:tag];
            //数据请求成功就缓存起来吧
            if (isCache) {
               [[TMCache sharedCache] setObject:responseObject forKey:caseKey];
            }
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //隐藏菊花
        [[HTFHudHelper sharedInstance]hideHud];
        if (self.delegate && [self.delegate respondsToSelector:@selector(requestFailed:tagNSString:)]) {
            [self.delegate requestFailed:error tagNSString:tag];
        }
        NSLog(@"operation: %@", operation.responseString);
        NSLog(@"Error: %@", error);
    }];
}

/**
 上传图片
 */
-(void)QZRequest_Upload_POST:(NSString *)urlString  parameters:(id)parameters imageData:(NSData *)path pathKey:(NSString *)key tagNSString:(NSString *)tag stopRequest:(BOOL)stop isSerializer:(BOOL)ser
{
    
    if (stop ==YES) {
        [_manager.operationQueue cancelAllOperations];
    }
    self.manager = [AFHTTPRequestOperationManager manager];
    
    //取消自动解析
    if (ser == YES) {
        self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    }else{
        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json",@"text/html", @"text/javascript", nil];
    }
    if (_isShowHUD) {
        //菊花
        [[HTFHudHelper sharedInstance]showHudAcitivityOnWindow];
    }

    
    AFHTTPRequestOperation *operation = [_manager POST:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (path) {
            NSDate *now = [NSDate date];
            NSDateFormatter *dateFormater = [[NSDateFormatter alloc] init];
            [dateFormater setDateFormat:@"yyyyMMddHHmmss"];

            NSString *fileName = [NSString stringWithFormat:@"%@.png",[dateFormater stringFromDate:now]];
            
            [formData appendPartWithFileData:path name:key fileName:fileName mimeType:@"image/png"];
        }
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //隐藏菊花
        [[HTFHudHelper sharedInstance]hideHud];
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(request_Upload_POST_FinishValue: tagNSString:)]) {
            [self.delegate request_Upload_POST_FinishValue:responseObject tagNSString:tag];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //隐藏菊花
        [[HTFHudHelper sharedInstance]hideHud];
        
        NSLog(@"Error: %@", error);
        NSLog(@"问题失败%@",operation);
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:@"操作失败,请检查网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        if (self.delegate && [self.delegate respondsToSelector:@selector(requestFailed: tagNSString:)]) {
            [self.delegate requestFailed:error tagNSString:tag];
        }
        
    }];
    [operation setUploadProgressBlock:^(NSUInteger __unused bytesWritten,
                                        long long totalBytesWritten,
                                        long long totalBytesExpectedToWrite) {
        NSLog(@"%lu",(unsigned long)bytesWritten);
        NSLog(@"Wrote %lld/%lld", totalBytesWritten, totalBytesExpectedToWrite);
        
        //[self.delegate setUploadProgress:totalBytesWritten andMax:totalBytesExpectedToWrite];
        
    }];
}

/*
 上传多张图片
 */
-(void)QZRequest_Uploads_POST :(NSString *)urlString parameters:(id)parameters tagNSString:(NSString *)tag file:(NSDictionary *)fileDic stopRequest:(BOOL)stop isSerializer:(BOOL)ser
{
    if (stop ==YES) {
        [_manager.operationQueue cancelAllOperations];
    }
    
    self.manager = [AFHTTPRequestOperationManager manager];
    //取消自动解析
    if (ser == YES) {
        self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    }else{
        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json",@"text/html", @"text/javascript", nil];
    }

    if (_isShowHUD) {
        //菊花
        [[HTFHudHelper sharedInstance]showHudAcitivityOnWindow];
    }
    
    AFHTTPRequestOperation *operation =[_manager POST:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSDate *now = [NSDate date];
        NSDateFormatter *dateFormater = [[NSDateFormatter alloc] init];
        [dateFormater setDateFormat:@"yyyyMMddHHmmss"];
        
        
        NSArray *keys = [fileDic allKeys];
        for (NSString *key in keys) {
            NSString *fileName = [NSString stringWithFormat:@"%@%@.png",[dateFormater stringFromDate:now],key];
            [formData appendPartWithFileData:fileDic[key] name:key fileName:fileName mimeType:@"image/png"];
        }
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //隐藏菊花
        [[HTFHudHelper sharedInstance]hideHud];
        
        NSLog(@"问题成功%@",operation);
        if(self.delegate && [self.delegate respondsToSelector:@selector(request_Uploads_POST_FinishValue: tagNSString:)] ){
            
            [self.delegate request_Uploads_POST_FinishValue:responseObject tagNSString:tag];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //隐藏菊花
        [[HTFHudHelper sharedInstance]hideHud];
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:@"操作失败,请检查网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        
        if(self.delegate && [self.delegate respondsToSelector:@selector(requestFailed: tagNSString:)] ){
            [self.delegate requestFailed:error tagNSString:tag];
        }
        NSLog(@"Error: %@", error);
        NSLog(@"问题失败%@",operation);
        
        
    }];
    
    [operation setUploadProgressBlock:^(NSUInteger __unused bytesWritten,
                                        long long totalBytesWritten,
                                        long long totalBytesExpectedToWrite) {
        NSLog(@"%lu",(unsigned long)bytesWritten);
        NSLog(@"Wrote %lld/%lld", totalBytesWritten, totalBytesExpectedToWrite);
        
        if(self.delegate && [self.delegate respondsToSelector:@selector(setUploadProgress: andMax:)] ){
            [self.delegate setUploadProgress:totalBytesWritten andMax:totalBytesExpectedToWrite];
        }
        
    }];
    
    // 5. Begin!
    [operation start];
}
@end
